// pages/personApplication/personApplication.js
const db = wx.cloud.database()
import common from "../../utils/getcurrentTime.js"

Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex:0,
    navTitle:["待处理","已完成"],
    currentInfoIndex:0,
    currentInfo:{},
    checkingInfo:[],
    checkedInfo:[]
  },

  /**
   * 数据初始化
   */
  onShow(){
   this.getStoreInfo()
  },

  /**
   * 获取并更新云端店铺申请数据
   */
  getStoreInfo(){
    wx.cloud.callFunction({
      name:"getAllStoreInfo"
    }).then(res=>{
      let {checkingInfo,checkedInfo} = res.result
      let index = this.data.currentInfoIndex
      this.setData({
        checkingInfo:checkingInfo.data,
        checkedInfo:checkedInfo.data,
        currentInfo:checkingInfo.data[index],
        total:checkingInfo.data.length,
        currentInfoIndex:0,
      })
    }).catch(error=>{
      console.log(error)
    })
  },
  /**
   * 点击导航栏
   */
  changeToActive(e){
    let activeIndex = e.currentTarget.id
    this.setData({
      activeIndex:activeIndex
    })
  },

  /**
   * 移动页面
   */
  changePages(e){
    let activeIndex = e.detail.currentItemId
    this.setData({
      activeIndex:activeIndex
    })
  },

  /**
   * 跳转至下一条申请
   */
  toNextInfo(){
    let index = this.data.currentInfoIndex + 1
    if(index < this.data.total){
      let checkingInfo = this.data.checkingInfo
      this.setData({
        currentInfoIndex:index,
        currentInfo:checkingInfo[index]
      })
      wx.pageScrollTo({
        scrollTop:0,
      })
    }else{
      wx.showToast({
        title: '所有申请已完成',
        icon:"success"
      })
    }

  },
  /**
   * 批准申请
   */
  agree(){
    this.updateState(1)

    let phoneNumber = this.data.currentInfo.phoneNumber
    db.collection('userList').where({
      account:phoneNumber
    }).update({
      data:{
        userType:"正式商家"
      }
    })
  },

  /**
   * 驳回申请
   */
  disagree(){
    this.updateState(2)
  },

  /**
   * 同步更改云端店铺状态
   * @param {*} state 
   */
  updateState(state){
    let _id = this.data.currentInfo._id
    let dealtime = common.setDate(Date.now(),"Y-m-d H:i:s")
    db.collection('storeInfo').doc(_id).update({
      data:{
        checkingstate:state,
        dealtime:dealtime
      }
    }
    ).then(()=>{
      this.toNextInfo()
    })
  },
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getStoreInfo()
  },
})